//
//  EmotionTool.m
//  SinaWebo
//
//  Created by wwj on 16/5/16.
//  Copyright © 2016年 亦心. All rights reserved.
//

/*
 结构:
 1. 加载emoticons.plist拿到每组表情的路径
 
 emoticons.plist(字典)  存储了所有组表情的数据
 |----packages(字典数组)
 |-------id(存储了对应组表情对应的文件夹)
 
 2. 根据拿到的路径加载对应组表情的info.plist
 info.plist(字典)
 |----id(当前组表情文件夹的名称)
 |----group_name_cn(组的名称)
 |----emoticons(字典数组, 里面存储了所有表情)
 |----chs(表情对应的文字)
 |----png(表情对应的图片)
 |----code(emoji表情对应的十六进制字符串)
 */

#import "EmotionTool.h"
#import "EmotionModel.h"
#import "EmotionPageModel.h"
#import "NSRegularExpression+Extension.h"
#import "EmojTextAttachment.h"
#import "Urlstruct.h"
#import "Status.h"
#import "PageInfo.h"
#import <MJExtension.h>

#define EmotionLocalFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"emotion.data"]

@interface EmotionTool ()

@end

@implementation EmotionTool


+ (instancetype)sharedEmotion{
    static EmotionTool *sharedEmotion;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedEmotion = [[EmotionTool alloc] init];
    });
    
    return sharedEmotion;
}

- (NSMutableArray *)emotionPages{
    if (_emotionPages == nil) {
        _emotionPages = [NSMutableArray array];
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"emoticons" ofType:@"plist" inDirectory:@"Emoticons.bundle"]];
        NSArray *dataArray = dict[@"packages"];
        
        [self addRecentEmotion];
        
        for (NSDictionary *diction in dataArray) {
            NSString *emotionID = diction[@"id"];
            EmotionPageModel *emotionPage = [self laodEmotionsWithID:emotionID];
            [_emotionPages addObject:emotionPage];
        }
        
    }
    return _emotionPages;
}

#pragma mark 添加一个表情到最近表情组
-(void)addEmotion:(EmotionModel *)emotion{
    if (emotion == nil) return;
    EmotionPageModel *first = _emotionPages.firstObject;
    
    NSMutableArray *emotions = first.emoticons;
    
    if (emotion.isDelete) return;
    
    if (![emotions containsObject:emotion]){
        [emotions removeLastObject];
        [emotions addObject:emotion];
    }
    
    NSArray *dataArray = [emotions sortedArrayUsingComparator:^NSComparisonResult(EmotionModel *obj1, EmotionModel *obj2) {
        return obj1.time < obj2.time;
    }];
    NSMutableArray *data = [dataArray mutableCopy];
    [data removeLastObject];
    [data addObject:[EmotionModel emotionModle:TRUE]];
    first.emoticons = data;
    
    [NSKeyedArchiver archiveRootObject:first toFile:EmotionLocalFilePath];
}

#pragma mark 添加最近表情组
- (void)addRecentEmotion{
    EmotionPageModel *pageModel = [NSKeyedUnarchiver unarchiveObjectWithFile:EmotionLocalFilePath];
    if (pageModel == nil) {
        pageModel = [[EmotionPageModel alloc] init];
        pageModel.group_name_cn = @"最近";
        NSMutableArray *emotionArray = [NSMutableArray array];
        //追加空白按钮
        NSInteger count = emotionArray.count % 21;
        for (NSInteger jx = count; jx < 20; jx++) {
            [emotionArray addObject:[EmotionModel emotionModle:FALSE]];
        }
        EmotionModel *emotion = [EmotionModel emotionModle:TRUE];
        [emotionArray addObject:emotion];
        pageModel.emoticons = emotionArray;
    }
   [_emotionPages addObject:pageModel];
}

#pragma mark 根据ID加载Emonj
- (EmotionPageModel *)laodEmotionsWithID:(NSString *)packageID{
    NSString *inDirectory = [[self emotionPath] stringByAppendingPathComponent:packageID];
    NSString *filePath = [inDirectory stringByAppendingPathComponent:@"info.plist"];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    EmotionPageModel *pageModle = [EmotionPageModel mj_objectWithKeyValues: dict];
    
    NSMutableArray *modleArray = pageModle.emoticons;
    
    //追加删除按钮
    for (int index = 0; index < pageModle.emoticons.count; index++) {
        EmotionModel *model = modleArray[index];
        model.ID = pageModle.ID;
        model.emtionPath = [inDirectory stringByAppendingPathComponent:model.png];
        if ((index + 1) % 21 == 0) {
            [modleArray insertObject:[EmotionModel emotionModle:TRUE] atIndex:index];
        }
    }
    pageModle.emoticons = modleArray;
    
    //追加空白按钮
    NSInteger count = pageModle.emoticons.count % 21;
    for (NSInteger jx = count; jx < 20; jx++) {
        [modleArray addObject:[EmotionModel emotionModle:FALSE]];
    }
    [modleArray addObject:[EmotionModel emotionModle:TRUE]];
    pageModle.emoticons = modleArray;
   
    return pageModle;
}

- (NSString *)emotionPath{
    return [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Emoticons.bundle"];
}


- (NSAttributedString *)attributedString:(NSString *)str font:(UIFont *)font status:(Status *)status{
    if (str.length < 1) {
        return nil;
    }
    
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] initWithString:str];
   
    
    //匹配URL
    for (Urlstruct *webURL in status.url_struct) {
        if (webURL.short_url.length == 0) continue;
        if (webURL.url_title.length == 0) continue;
        NSString *urlTitle = webURL.url_title;
        if (urlTitle.length > 27) urlTitle = [[urlTitle substringToIndex:27] stringByAppendingString:@"💕💕💕"];
        NSRange searchRange = NSMakeRange(0, strM.string.length);
        do {
            NSRange range = [strM.string rangeOfString:webURL.short_url options:kNilOptions range:searchRange];
            if (range.location == NSNotFound) break;
            NSMutableAttributedString *replaceAttrStr = [[NSMutableAttributedString alloc] initWithString:urlTitle];
            if (webURL.url_type_pic) {
                EmojTextAttachment *attach = [EmojTextAttachment emojTextAttachmentWithURL:webURL.url_type_pic font:[UIFont systemFontOfSize:14]];
                NSAttributedString *imageAttr = [NSAttributedString attributedStringWithAttachment:attach];
                
                [replaceAttrStr addAttribute:NSForegroundColorAttributeName value:MyColor(65, 105, 159) range:NSMakeRange(0, replaceAttrStr.length)];
                [replaceAttrStr insertAttributedString:imageAttr atIndex:0];
                
                [strM replaceCharactersInRange:range withAttributedString:replaceAttrStr];
                
                searchRange.location = searchRange.location + (replaceAttrStr.length ? replaceAttrStr.length : 1);
                if (searchRange.location + 1 >= strM.length) break;
                searchRange.length = strM.length - searchRange.location;
            }
            
        } while (1);
    }
    
    //匹配#话题#
    NSArray<NSTextCheckingResult *> *topicResults =[[NSRegularExpression regexTopic] matchesInString:strM.string options:kNilOptions range:NSMakeRange(0, strM.string.length)];
    if (topicResults) {
        for (NSTextCheckingResult *result in topicResults) {
            [strM addAttribute:NSForegroundColorAttributeName value:MyColor(65, 105, 159) range:result.range];
        }
    }
    
    //匹配@
    NSArray<NSTextCheckingResult *> *atResults =[[NSRegularExpression regexAt] matchesInString:strM.string options:kNilOptions range:NSMakeRange(0, strM.string.length)];
    for (NSTextCheckingResult *result in atResults) {
        [strM addAttribute:NSForegroundColorAttributeName value:MyColor(65, 105, 159) range:result.range];
    }

    
    //匹配Emotion
    NSArray<NSTextCheckingResult *> *emotinResults = [[NSRegularExpression regexEmoticon] matchesInString:strM.string options:kNilOptions range:NSMakeRange(0, strM.string.length)];
    NSInteger eCount = emotinResults.count;
    while (eCount > 0) {
        NSTextCheckingResult *result = emotinResults[--eCount];
        if (result) {//strM attributedSubstringFromRange:<#(NSRange)#>
            NSAttributedString *emjStr = [strM attributedSubstringFromRange:result.range];
            EmotionModel *emjModel = [self emotionWithStr:emjStr.string];
            EmojTextAttachment *attach = [EmojTextAttachment emojTextAttachment:emjModel font:font];
            NSAttributedString *attachStr = [NSAttributedString attributedStringWithAttachment:attach];
            NSRange range = result.range;
            [strM replaceCharactersInRange:range withAttributedString:attachStr];
        }
    }
    
    [strM addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, strM.length)];
    
    return strM;
}

- (EmotionModel *)emotionWithStr:(NSString *)emjStr{
    for (EmotionPageModel *model in self.emotionPages) {
        for (EmotionModel *emodel in model.emoticons) {
            if (emodel.chs == nil) continue;
            if ([emjStr isEqualToString:emodel.chs]) {
                return emodel;
            }
        }
    }
    return nil;
}

@end
